package cn.lg.soar.common.util.trans.handler;

import cn.lg.soar.common.data.dict.DictItem;
import cn.lg.soar.common.data.dict.IDict;
import cn.lg.soar.common.util.trans.model.TranslateContext;

import java.lang.annotation.Annotation;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @author luguoxiang
 * @date 2022/8/31
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
public abstract class AbstractTranslateHandler<T> implements ITranslateHandler<T> {

    protected final Map<T, String> map;
    protected final Map<String, T> fmap;

    public AbstractTranslateHandler(Map<T, String> map) {
        if (map == null) {
            map = new HashMap<>();
        }
        this.map = new HashMap<>(map.size());
        this.fmap = new HashMap<>(map.size());
        map.forEach((k, v) -> {
            this.map.put(k, v);
            this.fmap.put(v, k);
        });
    }

    @Override
    public Object convertByJava(T javaValue, Annotation annotation, TranslateContext<T> context) {
        return map.get(javaValue);
    }

    @Override
    public T convertToJava(Object value, Annotation annotation, TranslateContext<T> context) {
        return fmap.get(value);
    }

    public IDict[] dicts() {
        IDict[] array = new IDict[map.size()];
        Set<Map.Entry<T, String>> entries = map.entrySet();
        int index = 0;
        for (Map.Entry<T, String> entry : entries) {
            array[index++] = new DictItem<>(entry.getKey(), entry.getValue());
        }
        return array;
    }

    public abstract String getCode();

}
